package io.fivefire.base.common.token;

import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author huijun
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            Token annotation = method.getAnnotation(Token.class);

            if (annotation != null) {

                String token = request.getHeader("token");

                if (token == null) {
                    response.setStatus(401);
                    return false;
                } else {
                    log.debug("tokenStr:" + token);
                }

                Claims claims1 = TokenMangager.getClaimsFromToken(token);
                if (claims1 != null) {
                    Long u = claims1.get(Constant.TOKEN_USER_ID, Long.class);
                    if (u != null) {
                        log.info("token检验成功");
                        return true;
                    }else {
                        response.setStatus(401);
                        return false;
                    }
                } else {
                    response.setStatus(401);
                    return false;
                }

            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
}
